package com.zhx.sweet.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author zhanghaixuan
 * 2017年11月04日22:40:55
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider{


    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;


        UserDetails user = userDetailsService.loadUserByUsername(smsCodeAuthenticationToken.getPrincipal().toString());

        if (user == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息!");
        }

        SmsCodeAuthenticationToken smsCode = new SmsCodeAuthenticationToken(user,user.getAuthorities());

        smsCode.setDetails(smsCodeAuthenticationToken.getDetails());

        return smsCode;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
